package com.huang.advice;

import com.huang.anno.ResponseResult;
import com.huang.domain.ResultObject;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 统一封装返回格式，但每次需要反射判断是否有ResponseResult注解，可能存在性能问题可以考虑做个状态表记录一下
 */
@RestControllerAdvice
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return AnnotatedElementUtils.hasAnnotation(methodParameter.getContainingClass(), ResponseResult.class)
                || methodParameter.hasMethodAnnotation(ResponseResult.class);
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if (o instanceof ResultObject) {
            return o;
        }
        return ResultObject.success(o);
    }
}
